package com.frogs.ucenter.v1.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.ApplicablePlatformEnum;
import com.frogs.system.util.ExpandCodeEnum;
import com.frogs.system.util.IntegralExchangeConditionTypeEnum;
import com.frogs.system.util.IntegralExchangeTargetEnum;
import com.frogs.system.util.RechargeBalanceStatusEnum;
import com.frogs.system.util.UserAccountInfoStatusEnum;
import com.frogs.system.util.UserIntegralConsumeEnum;
import com.frogs.system.util.UserIntegralRecordEnum;
import com.frogs.system.util.UserMessageTypeEnum;
import com.frogs.system.util.UserTypeEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.component.RequestApiHelper;
import com.frogs.ucenter.component.UserMessageDmHelper;
import com.frogs.ucenter.dao.InsuranceCodeDao;
import com.frogs.ucenter.dao.IntegralConsumeRelationDao;
import com.frogs.ucenter.dao.IntegralPromotionGoodsRelationDao;
import com.frogs.ucenter.dao.UserAccountInfoDao;
import com.frogs.ucenter.dao.UserIntegralBalanceDao;
import com.frogs.ucenter.dao.UserIntegralConsumeBackDao;
import com.frogs.ucenter.dao.UserIntegralConsumeBlockingDao;
import com.frogs.ucenter.dao.UserIntegralConsumeRecordDao;
import com.frogs.ucenter.dao.UserIntegralMoneyRelationDao;
import com.frogs.ucenter.dao.UserIntegralRecordDao;
import com.frogs.ucenter.dao.UserLevelInfoDao;
import com.frogs.ucenter.entity.InsuranceCode;
import com.frogs.ucenter.entity.IntegralConsumeRelation;
import com.frogs.ucenter.entity.IntegralPromotionGoodsRelation;
import com.frogs.ucenter.entity.UserAccountInfo;
import com.frogs.ucenter.entity.UserIntegralBalance;
import com.frogs.ucenter.entity.UserIntegralConsumeBack;
import com.frogs.ucenter.entity.UserIntegralConsumeBlocking;
import com.frogs.ucenter.entity.UserIntegralConsumeRatioInfo;
import com.frogs.ucenter.entity.UserIntegralConsumeRecord;
import com.frogs.ucenter.entity.UserIntegralMoneyRelation;
import com.frogs.ucenter.entity.UserIntegralRecord;
import com.frogs.ucenter.entity.UserLevelInfo;
import com.frogs.ucenter.v1.request.IntegralConsumeRatioRequest;
import com.frogs.ucenter.v1.request.IntegralConsumeRecordRequest;
import com.frogs.ucenter.v1.request.IntegralExchangeCDkeyRequest;
import com.frogs.ucenter.v1.request.IntegralExchangeCouponRequest;
import com.frogs.ucenter.v1.request.IntegralExchangeRequest;
import com.frogs.ucenter.v1.request.UserIntegralBalanceBlockingRequest;
import com.frogs.ucenter.v1.request.UserIntegralBalanceReleaseRequest;
import com.frogs.ucenter.v1.request.UserIntegralBalanceUnfreezeRequest;
import com.frogs.ucenter.v1.request.UserIntegralConsumeBackRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.PageListResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.response.UpdateResponse;
import com.frogs.ucenter.v1.service.UserIntegralExchangeService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"userIntegralExchangeService")
public class UserIntegralExchangeServiceImpl implements UserIntegralExchangeService {

	private static final Logger log = LoggerFactory.getLogger(UserIntegralExchangeServiceImpl.class);
	
	@Resource
	private IntegralPromotionGoodsRelationDao integralPromotionGoodsRelationDao;
	@Resource
	private IntegralConsumeRelationDao integralConsumeRelationDao;
	@Resource
	private UserIntegralMoneyRelationDao userIntegralMoneyRelationDao;
	@Resource
	private UserIntegralBalanceDao userIntegralBalanceDao;
	@Resource
	private UserAccountInfoDao userAccountInfoDao;
	@Resource
	private UserIntegralConsumeBackDao userIntegralConsumeBackDao;
	@Resource
	private UserIntegralConsumeBlockingDao userIntegralConsumeBlockingDao;
	@Resource
	private UserIntegralConsumeRecordDao userIntegralConsumeRecordDao;
	@Resource
	private UserIntegralRecordDao userIntegralRecordDao;
	@Resource
	private UserLevelInfoDao userLevelInfoDao;
	@Resource
	private InsuranceCodeDao insuranceCodeDao;
	@Resource
	private RequestApiHelper requestApiHelper;
	@Resource
	private UserMessageDmHelper userMessageDmHelper;
	
	/**
	 * 获取兑换优惠券或商品， 需要调整
	 */
	@Override
	public Response getIntegralExchangeList(Request request) throws Exception  {
		PageListResponse<IntegralPromotionGoodsRelation> response = new PageListResponse<IntegralPromotionGoodsRelation>();
		try {
			IntegralExchangeRequest exchangeRequest = (IntegralExchangeRequest) request;
			Integer type = exchangeRequest.getType();
			Integer isVip = exchangeRequest.getIsVip();
			Integer columnId = exchangeRequest.getColumnId();
			Map<String, Object> params = new HashMap<String, Object>();
			if(type > 0) {
				params.put("eqRelationType", type);
			}
			if (isVip == UserAccountInfoStatusEnum.VIP_YES.getId()) {
				List<Integer> levelIds = new ArrayList<Integer>();
				levelIds.add(UserTypeEnum.VIP1.getType());
				levelIds.add(UserTypeEnum.VIP2.getType());
				levelIds.add(UserTypeEnum.VIP3.getType());
				params.put("inLevelIdList", levelIds);
			}
			if(!StringUtil.isEmpty( columnId )) {
				params.put("eqColumnId", columnId);
			}
			PageList<IntegralPromotionGoodsRelation> list = integralPromotionGoodsRelationDao.selectByMap(params, exchangeRequest.getPageNo(), exchangeRequest.getPageSize());
			response.setList(list);
			response.setPageTurn(list.getPageTurn());
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 获取用户积分和兑换规则
	 * 旧接口，暂未用到
	 */
	@Override
	public Response getIntegralConsumeRatio(Request request) throws Exception  {
		ShowResponse<UserIntegralConsumeRatioInfo> response = new ShowResponse<UserIntegralConsumeRatioInfo>();
		try {
			IntegralConsumeRatioRequest consumeRatioRequest = (IntegralConsumeRatioRequest) request;
			Integer userId = consumeRatioRequest.getUserId();
			UserLevelInfo userLevelInfo = userLevelInfoDao.selectById(userId);
			UserIntegralConsumeRatioInfo consumeRatioInfo = new UserIntegralConsumeRatioInfo();
			
			this.getIntegralConsumeRelation(consumeRatioInfo, userLevelInfo);
			this.getUserIntegralMoneyRelation(consumeRatioInfo, userLevelInfo);
			UserIntegralBalance integral = userIntegralBalanceDao.selectById(userId);
			if (integral != null) {
				consumeRatioInfo.setUserIntegral(integral.getIntegralUsable());
			}
			
			response.setInfo(consumeRatioInfo);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	private void getIntegralConsumeRelation(UserIntegralConsumeRatioInfo consumeRatioInfo, UserLevelInfo userLevelInfo) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqType", IntegralExchangeConditionTypeEnum.OFFSET_AMOUNT.getId());
		params.put("eqLevelId", userLevelInfo.getLevelId());
		PageList<IntegralConsumeRelation> list = integralConsumeRelationDao.selectByMap(params, false);
		consumeRatioInfo.setLevelId(userLevelInfo.getLevelId());
		if (list.size() == 0) {
			params.put("eqLevelId", UserTypeEnum.ALL.getType());
			list = integralConsumeRelationDao.selectByMap(params, false);
		}
		if (list.size() > 0) {
			IntegralConsumeRelation integralConsumeRelation = list.get(0);
			consumeRatioInfo.setRatio(integralConsumeRelation.getRatio());
			consumeRatioInfo.setRemark(integralConsumeRelation.getRemark());
			consumeRatioInfo.setRebate(integralConsumeRelation.getRebate());
		}
	}
	
	private void getUserIntegralMoneyRelation(UserIntegralConsumeRatioInfo consumeRatioInfo, UserLevelInfo userLevelInfo) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqLevelId", userLevelInfo.getLevelId());
		PageList<UserIntegralMoneyRelation> moneyRelations = userIntegralMoneyRelationDao.selectByMap(params, false);
		if (moneyRelations.size() == 0) {
			params.put("eqLevelId", UserTypeEnum.ALL.getType());
			moneyRelations = userIntegralMoneyRelationDao.selectByMap(params, false);
		} 
		if (moneyRelations.size() > 0) {
			UserIntegralMoneyRelation userIntegralMoneyRelation = moneyRelations.get(0);
			consumeRatioInfo.setIntegralNum(userIntegralMoneyRelation.getIntegralNum());
			consumeRatioInfo.setExchangeMoney(userIntegralMoneyRelation.getExchangeMoney());
		} else {
			consumeRatioInfo.setIntegralNum(0);
			consumeRatioInfo.setExchangeMoney(0);
		}
	}
	
	/**
	 * 冻结积分
	 */
	@Override
	public Response blockingIntegralBalance(Request request) throws Exception  {
		AddResponse<UserIntegralConsumeBlocking> blockingResponse = new AddResponse<UserIntegralConsumeBlocking>(); 
		try {
			UserIntegralBalanceBlockingRequest blockingRequest = (UserIntegralBalanceBlockingRequest) request;
			Integer userId = blockingRequest.getUserId();
			UserAccountInfo userAccountInfo = userAccountInfoDao.selectById(userId);
			if (userAccountInfo == null) {
				throw new ServiceOperationException("该用户不存在");
			}
			UserIntegralConsumeBlocking consumeBlocking = mergeBlockingBalance(userId, blockingRequest.getOrderId(), blockingRequest.getConsumeIntegral(),
					blockingRequest.getExpandCode(), blockingRequest.getApplicablePlatformId(), RechargeBalanceStatusEnum.BLOCKING.getId());
			blockingResponse.setInfo(consumeBlocking);
			blockingResponse.setTip("成功冻结积分" + blockingRequest.getConsumeIntegral());
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		
		return blockingResponse;
	}
	
	/**
	 * 解冻积分
	 */
	@Override
	public Response unfreezeIntegralBalance(Request request) throws Exception  {
		UpdateResponse<UserIntegralConsumeBlocking> unfreezeResponse = new UpdateResponse<UserIntegralConsumeBlocking>();
		try {
			UserIntegralBalanceUnfreezeRequest unfreezeRequest = (UserIntegralBalanceUnfreezeRequest) request;
			UserAccountInfo userAccountInfo = userAccountInfoDao.selectById(unfreezeRequest.getUserId());
			if (userAccountInfo == null) {
				throw new ServiceOperationException("该用户不存在");
			}
			
			UserIntegralConsumeBlocking consumeBlocking = mergeBlockingBalance(unfreezeRequest.getUserId(), unfreezeRequest.getOrderId(),unfreezeRequest.getConsumeIntegral(),
					unfreezeRequest.getExpandCode(), unfreezeRequest.getApplicablePlatformId(), RechargeBalanceStatusEnum.UNFREEZE.getId());
			unfreezeResponse.setInfo(consumeBlocking);
			unfreezeResponse.setTip("成功解冻积分" + unfreezeRequest.getConsumeIntegral());
			
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return unfreezeResponse;
	}
	
	/**
	 * 清除冻结积分
	 */
	@Override
	public Response releaseBlockingBalance(Request request) throws Exception  {
		UpdateResponse<UserIntegralConsumeBlocking> releaseResponse = new UpdateResponse<UserIntegralConsumeBlocking>();
		try {
			UserIntegralBalanceReleaseRequest releaseRequest = (UserIntegralBalanceReleaseRequest) request;
			UserAccountInfo userAccountInfo = userAccountInfoDao.selectById(releaseRequest.getUserId());
			if (userAccountInfo == null) {
				throw new ServiceOperationException("该用户不存在");
			}
			
			UserIntegralConsumeBlocking consumeBlocking = mergeBlockingBalance(releaseRequest.getUserId(), releaseRequest.getOrderId(),releaseRequest.getConsumeIntegral(),
					releaseRequest.getExpandCode(), releaseRequest.getApplicablePlatformId(), RechargeBalanceStatusEnum.RELEASE.getId());
			
			releaseResponse.setInfo(consumeBlocking);
			releaseResponse.setTip("成功消费冻结积分" + releaseRequest.getConsumeIntegral());
			
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return releaseResponse;
	}
	
	/**
	 * 积分抵制余额回滚
	 */
	@Override
	public Response integralConsumeBack(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			UserIntegralConsumeBackRequest backRequest = (UserIntegralConsumeBackRequest) request;
			int userId = backRequest.getUserId();
			String orderId = backRequest.getOrderId();
			//1、判断是否存在,不存在则返回不存在记录
			//2、判断是否回滚过，已回滚过则返回已经回滚过
			//3、更改积分记录，添加回滚记录
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("eqOrderId", orderId);
			params.put("eqUserId", userId);
			PageList<UserIntegralConsumeRecord> list = userIntegralConsumeRecordDao.selectByMap(params, false);
			if(list.size()>0){
				params = new HashMap<String,Object>();
				params.put("eqOrderId", orderId);
				PageList<UserIntegralConsumeBack> backList = userIntegralConsumeBackDao.selectByMap(params, false);
				if(backList.size()>0){
					response.setTip("该订单已经回滚过");
				}else{
					UserIntegralConsumeRecord userIntegralConsumeRecord = list.get(0);
					int integralNum = userIntegralConsumeRecord.getIntegralNum();//需回滚的积分
					String remark = "抵制消费余额回滚";
					String expandCode = ExpandCodeEnum.MALL.getId();
					int applicablePlatformId = ApplicablePlatformEnum.WEB.getId();
					int type = UserIntegralRecordEnum.BACK_DONATE.getId();
					//增加积分记录
					insertIntegralRecord( integralNum, remark, expandCode, applicablePlatformId, userId, type, orderId);
					//修改积分余额
					restorebalance(integralNum, userId);
					//增加回滚记录
					UserIntegralConsumeBack userIntegralConsumeBack = new UserIntegralConsumeBack();
					userIntegralConsumeBack.setOrderId(orderId);
					userIntegralConsumeBackDao.insert(userIntegralConsumeBack);
					response.setTip("积分回滚成功");
				}
			}else{
				response.setTip("不存在相应的订单记录");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 积分兑换卡券
	 */
	@Override
	public Response integralExchangeCoupon(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			IntegralExchangeCouponRequest  exchangeCouponRequest = (IntegralExchangeCouponRequest) request;
			Integer userId = exchangeCouponRequest.getUserId();
			Integer id = exchangeCouponRequest.getId();
			String expandCode = exchangeCouponRequest.getExpandCode();
			String orderId = "";//卡券没有orderId，登记为空
			Integer applicablePlatformId = exchangeCouponRequest.getApplicablePlatformId();
			UserLevelInfo userLevelInfo = userLevelInfoDao.selectById(userId);	
			if(userLevelInfo == null) {
				throw new ServiceOperationException("用户等级不存在");
			}
			
			IntegralPromotionGoodsRelation integralPromotionGoodsRelation = integralPromotionGoodsRelationDao.selectById(id);
			if(!(integralPromotionGoodsRelation.getRelationType() == IntegralExchangeTargetEnum.COUPON.getId())) {
				throw new ServiceOperationException("非积分兑换卡券");
			}
			if(integralPromotionGoodsRelation.getLevelId() != UserTypeEnum.ALL.getType() && !(userLevelInfo.getLevelId() >= integralPromotionGoodsRelation.getLevelId())) {
				throw new ServiceOperationException("不符合积分兑换卡券的等级要求");
			}
			
			Integer cardId = integralPromotionGoodsRelation.getRelationId();
			Integer consumeIntegral = integralPromotionGoodsRelation.getIntegralNum(); 			
			balanceConsumeVerify(consumeIntegral, userId);
			insertConsumeRecord(userId, consumeIntegral, expandCode, applicablePlatformId, UserIntegralConsumeEnum.TO_COUPON.getId(), "积分兑换卡券", orderId);

			JSONObject result = requestApiHelper.giveCard(userId, cardId);
			log.info("func[integralExchangeCoupon] result["+result+"] desc[get card]");
			int status = result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName());
			//ApiResultEnum
			if(status != ApiResultEnum.SUCCESS.getId()) {
				throw new ServiceOperationException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			}
			
			response.setCode(ApiResultEnum.SUCCESS.getId());
			response.setTip("兑换卡券成功");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 积分兑换激活码
	 */
	@Override
	public Response integralExchangeCDkey(Request request) throws Exception  {
		ShowResponse<String> response = new ShowResponse<String>();
		try {
			IntegralExchangeCDkeyRequest  exchangeCDkeyRequest = (IntegralExchangeCDkeyRequest) request;
			Integer userId = exchangeCDkeyRequest.getUserId();
			Integer id = exchangeCDkeyRequest.getId();
			String expandCode = exchangeCDkeyRequest.getExpandCode();
			Integer applicablePlatformId = exchangeCDkeyRequest.getApplicablePlatformId();
			UserLevelInfo userLevelInfo = userLevelInfoDao.selectById(userId);	
			if(userLevelInfo == null) {
				throw new ServiceOperationException("用户等级不存在");
			}
			
			IntegralPromotionGoodsRelation integralPromotionGoodsRelation = integralPromotionGoodsRelationDao.selectById(id);
			if(!(integralPromotionGoodsRelation.getRelationType() == IntegralExchangeTargetEnum.CDKEY.getId())) {
				throw new ServiceOperationException("非积分兑换激活码");
			}
			if(integralPromotionGoodsRelation.getLevelId() != UserTypeEnum.ALL.getType() && !(userLevelInfo.getLevelId() >= integralPromotionGoodsRelation.getLevelId())) {
				throw new ServiceOperationException("不符合积分兑换激活码的等级要求");
			}
			Integer insuranceId = integralPromotionGoodsRelation.getRelationId();
			Integer consumeIntegral = integralPromotionGoodsRelation.getIntegralNum(); 			
			balanceConsumeVerify(consumeIntegral, userId);
			insertConsumeRecord(userId, consumeIntegral, expandCode, applicablePlatformId, UserIntegralConsumeEnum.TO_CDKEY.getId(), "积分兑换保险激活码", "");
			String code = this.createCDkey(userId, insuranceId);
			String subject = "积分兑换激活码通知";
			String content = "亲爱的用户，您好！您已使用积分兑换激活码，激活码为："+ code + "。您可以使用该激活码购买相应的保险！<a href='http://ucenter.ehaoyao.com/insurance/index.html' target='_blank' style='color:#f15a28'>购买入口</a>";
			JSONArray array = new JSONArray();
			JSONObject object = new JSONObject();
			object.put("receiver", "");
			object.put("receiverId", userId);
			array.add(object);
			userMessageDmHelper.sendToUser(subject, content, "", "", "系统发送", 
					"-1", array, UserMessageTypeEnum.RECEIVER_PERSONAL.getId(), ApplicablePlatformEnum.WEB.getId());
			response.setTip("兑换激活码成功");
			response.setInfo(code);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 生成激活码
	 * 
	 * @param userId
	 * @param insuranceId
	 */
	private String createCDkey(Integer userId, Integer insuranceId) {
		String code = StringUtil.getRandomString(4) + new Date().getTime() + StringUtil.getRandomString(4);
		InsuranceCode insuranceCode = new InsuranceCode();
		insuranceCode.setCode(code);
		insuranceCode.setUserId(userId);
		insuranceCode.setInsuranceId(insuranceId);
		insuranceCodeDao.insert(insuranceCode);
		return code;
	}
	
	/**
	 * 修改冻结记录
	 * 
	 * @param userId
	 * @param orderId
	 * @param consumeIntegral
	 * @return
	 * @throws Exception
	 */
	private UserIntegralConsumeBlocking mergeBlockingBalance(Integer userId, String orderId, Integer consumeIntegral, String expandCode, Integer applicablePlatformId, int status) throws Exception {
		Map<String, Object> params = new HashMap<String,Object>();
		params.put("eqOrderId", orderId);
		params.put("eqUserId", userId);
		PageList<UserIntegralConsumeBlocking> list = userIntegralConsumeBlockingDao.selectByMap(params, false);
		UserIntegralConsumeBlocking consumeBlocking = null;
		UserIntegralBalance userIntegralBalance = userIntegralBalanceDao.selectById(userId);
		boolean exist = true;
		boolean needUpdate = true;
		Integer tmpBalance = 0;
		if(list.size() > 0) {
			consumeBlocking = list.get(0);
			if(consumeBlocking.getUserId().compareTo(userId) != 0) {
				throw new Exception("无权限操作!");
			}
			if(status == consumeBlocking.getStatus()) {
				if(consumeIntegral.equals(consumeBlocking.getIntegralNum())) {
					needUpdate = false;
				} else {
					tmpBalance = consumeBlocking.getIntegralNum();
				}
			}
		} else {
			consumeBlocking = new UserIntegralConsumeBlocking();
			exist = false;
		}
		
		if(exist) {
			if(RechargeBalanceStatusEnum.RELEASE.getId() == status 
					&& consumeBlocking.getStatus() != RechargeBalanceStatusEnum.BLOCKING.getId()) {
				throw new ServiceOperationException("不存在冻结积分，请确认！");
			}
			if(RechargeBalanceStatusEnum.UNFREEZE.getId() == status 
					&& consumeBlocking.getStatus() != RechargeBalanceStatusEnum.BLOCKING.getId()) {
				throw new ServiceOperationException("不存在冻结积分，请确认！");
			}
		}
		
		if(needUpdate) {
			consumeBlocking.setIntegralNum(consumeIntegral);
			consumeBlocking.setCreateTime(new Date());
			consumeBlocking.setOrderId(orderId);
			consumeBlocking.setUserId(userId);
			consumeBlocking.setStatus(status);
			String remark = "";
			int type = UserIntegralRecordEnum.ORDER_EXCHANGE.getId();//积分来源
			if(!exist && RechargeBalanceStatusEnum.BLOCKING.getId() == status) {
				userIntegralConsumeBlockingDao.insert(consumeBlocking);
			} else if(!exist && RechargeBalanceStatusEnum.BLOCKING.getId() != status) {
				throw new Exception("该订单没有冻结记录!");
			} else if(exist){
				if(RechargeBalanceStatusEnum.BLOCKING.getId() == status) {
					remark = "更新积分";
					restorebalance(tmpBalance, userId);
					insertIntegralRecord(tmpBalance, remark, expandCode, applicablePlatformId, userId, type, orderId);
				}
				userIntegralConsumeBlockingDao.update(consumeBlocking);
			}
			if(RechargeBalanceStatusEnum.BLOCKING.getId() == status) {
				//从积分余额减去相应的积分
				remark = "成功完成一次兑换";
				userIntegralBalance = balanceConsumeVerify(consumeIntegral, userId);
				insertConsumeRecord(userId, consumeIntegral, expandCode, applicablePlatformId,UserIntegralConsumeEnum.TO_ORDER.getId(), remark, orderId);
			} else if(RechargeBalanceStatusEnum.UNFREEZE.getId() == status) {
				//增加相应积分
				remark = "兑换失败，哇币返还";
				userIntegralBalance = restorebalance(consumeIntegral, userId);
				insertIntegralRecord(consumeIntegral, remark, expandCode, applicablePlatformId, userId, type, orderId);
			}
		}
		if (userIntegralBalance!=null) {
			consumeBlocking.setIntegralUsable(userIntegralBalance.getIntegralUsable()); 
		}else {
			consumeBlocking.setIntegralUsable(0);
		}
		return consumeBlocking;
	}
	
	/**
	 * 插入消费记录
	 * 
	 * @param balanceConsumeRequest
	 */
	private void insertConsumeRecord(Integer userId, Integer consumeIntegral, String expandCode, Integer applicablePlatformId, Integer consumeType, String remark, String orderId) {
		UserIntegralConsumeRecord userIntegralConsumeRecord = new UserIntegralConsumeRecord();
		userIntegralConsumeRecord.setUserId(userId);
		userIntegralConsumeRecord.setIntegralNum(consumeIntegral);
		userIntegralConsumeRecord.setConsumeTime(new Date());
		userIntegralConsumeRecord.setExpandCode(expandCode);
		userIntegralConsumeRecord.setApplicablePlatformId(applicablePlatformId);
		userIntegralConsumeRecord.setType(consumeType);
		userIntegralConsumeRecord.setRemark(remark);
		userIntegralConsumeRecord.setOrderId(orderId);
		userIntegralConsumeRecordDao.insert(userIntegralConsumeRecord);
	}
	
	/**
	 * 插入积分充值记录
	 * 
	 * @param integralNum
	 * @param remark
	 * @param expandCode
	 * @param userId
	 */
	private void insertIntegralRecord(Integer integralNum, String remark, String expandCode, Integer applicablePlatformId, Integer userId, Integer type, String orderId) {
		UserIntegralRecord userIntegralRecord = new UserIntegralRecord();
		userIntegralRecord.setIntegralNum(integralNum);
		userIntegralRecord.setIntegralTime(new Date());
		userIntegralRecord.setRemark(remark);
		userIntegralRecord.setExpandCode(expandCode);
		userIntegralRecord.setApplicablePlatformId(applicablePlatformId);
		userIntegralRecord.setType(type);
		userIntegralRecord.setUserId(userId);
		userIntegralRecord.setOrderId(orderId);
		userIntegralRecordDao.insert(userIntegralRecord);
	}
	
	/**
	 * 积分消费检测
	 * 扣积分
	 * 
	 * @param consumeIntegral
	 * @param userId
	 */
	private UserIntegralBalance balanceConsumeVerify(Integer consumeIntegral, Integer userId) throws Exception  {
		Map<String, Object> param = new HashMap<String, Object>();
		UserIntegralBalance userIntegralBalance = userIntegralBalanceDao.selectById(userId);
		if(null != userIntegralBalance) {
			Integer balance = userIntegralBalance.getIntegralUsable();
			Integer integralUsed = userIntegralBalance.getIntegralUsed();
			param.put("eqId", userId);
			param.put("getIntegralUsable", consumeIntegral);
			param.put("integralUsable", balance - consumeIntegral);
			param.put("integralUsed", integralUsed + consumeIntegral);
			param.put("updateTime", new Date());
			if(userIntegralBalanceDao.updateByMap(param) < 1) {
				throw new ServiceOperationException("积分不足");
			}
			return userIntegralBalanceDao.selectById(userId);
		} else {
			log.error("func[balanceConsumeVerify] userId[" + userId + "] desc[该账户没积分]");
			throw new ServiceOperationException("该账户没积分");
		}
	}
	
	/**
	 * 恢复积分检测
	 * 
	 * @param consumeIntegral
	 * @param userId
	 */
	private UserIntegralBalance restorebalance(Integer consumeIntegral, Integer userId) throws Exception  {
		UserIntegralBalance userIntegralBalance = userIntegralBalanceDao.selectById(userId);
		if (null != userIntegralBalance) {
			Integer balance = userIntegralBalance.getIntegralUsable();
			Integer integralUsed = userIntegralBalance.getIntegralUsed();
			userIntegralBalance.setIntegralUsable(balance + consumeIntegral);
			userIntegralBalance.setIntegralUsed(integralUsed - consumeIntegral);
			userIntegralBalance.setUpdateTime(new Date());
			userIntegralBalanceDao.update(userIntegralBalance);
			return userIntegralBalanceDao.selectById(userId);
		} else {
			log.error("func[restorebalance] userId[" + userId + "] desc[该账户没积分]");
			throw new ServiceOperationException("该账户没积分");
		}
	}

	@Override
	public Response getIntegralConsumeByOrderSn(Request request) throws Exception {
		ShowResponse<UserIntegralConsumeBlocking> response = new ShowResponse<UserIntegralConsumeBlocking>();
		try {
			IntegralConsumeRecordRequest consumeRecordRequest = (IntegralConsumeRecordRequest) request;
			String orderId = consumeRecordRequest.getOrderId();
			
			UserIntegralConsumeBlocking consumeBlocking = userIntegralConsumeBlockingDao.selectByOrderId(orderId);
			if (consumeBlocking != null) {
				response.setInfo(consumeBlocking);
			}
			
			
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
}
